/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package CL;

import EL.FoodTypes;
import EL.Foods;
import EL.TableTypes;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import slsBeans.*;

/**
 *
 * @author Tian
 */
public class FoodCO extends HttpServlet
{

    private FoodBLORemote rFood;
    private FoodTypeBLORemote rFoodType;

    @Override
    public void init() throws ServletException
    {
        try
        {
            super.init();
            String jndiFileName = this.getServletContext().getRealPath("/") + "/WEB-INF/jndi.properties";
            Properties props = new Properties();
            props.load(new FileInputStream(jndiFileName));
            InitialContext ctx = new InitialContext(props);
            rFood = (FoodBLORemote) ctx.lookup("FoodBLO/remote");
            rFoodType = (FoodTypeBLORemote) ctx.lookup("FoodTypeBLO/remote");
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        String action = request.getParameter("action");
        if (action.equalsIgnoreCase("getAll"))
        {
            List<Foods> foods = rFood.getAll();
            request.setAttribute("foods", foods);
            RequestDispatcher rd = request.getRequestDispatcher("ad_Food_Viewing.jsp");
            rd.forward(request, response);
        }
        else if (action.equalsIgnoreCase("formAddNew"))
        {
            List<FoodTypes> foodTypes = rFoodType.getAll();
            request.setAttribute("foodTypes", foodTypes);
            RequestDispatcher rd = request.getRequestDispatcher("ad_Food_Adding.jsp");
            rd.forward(request, response);
        }
        else if (action.equalsIgnoreCase("add"))
        {
            if (ServletFileUpload.isMultipartContent(request))
            {
                ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
                List items = null;
                try
                {
                    items = upload.parseRequest(request);
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }

                String imgPath = "";
                Hashtable params = new Hashtable();
                Iterator iter = items.iterator();
                while (iter.hasNext())
                {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField())
                    {
                        params.put(item.getFieldName(), item.getString());
                    }
                    else
                    {
                        String fileName = item.getName();
                        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                        imgPath = "images/" + fileName;
                        String realPath = this.getServletContext().getRealPath("/") + imgPath;
                        File fileUpload = new File(realPath);
                        try
                        {
                            item.write(fileUpload);
                        }
                        catch (Exception ex)
                        {
                            ex.printStackTrace();
                        }
                    }
                }
                String foodName = (String) params.get("txtFoodName");
                String foodTypeID = (String) params.get("cbbFoodType");
                String price = (String) params.get("txtPrice");
                String vegetarian = (String) params.get("ckbVegetarian");
                boolean isVegetarian = false;
                if (vegetarian != null)
                {
                    isVegetarian = true;
                }
                FoodTypes ft = rFoodType.getByID(Integer.parseInt(foodTypeID));

                Foods f = new Foods(Float.parseFloat(price), foodName, isVegetarian, imgPath);

                boolean result = rFood.add(f, ft);
                if (result)
                {
                    response.sendRedirect("FoodCO?action=getAll");
                }
                else
                {
                    response.sendRedirect("FoodCO?action=formAddNew");
                }
            }
        }
        else if (action.equalsIgnoreCase("formEdit"))
        {
            String id = request.getParameter("id");
            Foods food = rFood.getByID(Integer.parseInt(id));
            List<FoodTypes> foodTypes = rFoodType.getAll();
            request.setAttribute("foodTypes", foodTypes);
            request.setAttribute("food", food);
            RequestDispatcher rd = request.getRequestDispatcher("ad_Food_Editing.jsp");
            rd.forward(request, response);
        }
        else if (action.equalsIgnoreCase("formEditImage"))
        {
            String id = request.getParameter("id");
            Foods food = rFood.getByID(Integer.parseInt(id));
            request.setAttribute("food", food);
            RequestDispatcher rd = request.getRequestDispatcher("ad_Food_ImageEditing.jsp");
            rd.forward(request, response);
        }
        else if (action.equalsIgnoreCase("editImage"))
        {

            if (ServletFileUpload.isMultipartContent(request))
            {
                ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
                List items = null;
                try
                {
                    items = upload.parseRequest(request);
                }
                catch (Exception ex)
                {
                    ex.printStackTrace();
                }

                String imgPath = "";
                Hashtable params = new Hashtable();
                Iterator iter = items.iterator();
                while (iter.hasNext())
                {
                    FileItem item = (FileItem) iter.next();
                    if (item.isFormField())
                    {
                        params.put(item.getFieldName(), item.getString());
                    }
                    else
                    {
                        String fileName = item.getName();
                        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                        imgPath = "images/" + fileName;
                        String realPath = this.getServletContext().getRealPath("/") + imgPath;
                        File fileUpload = new File(realPath);
                        try
                        {
                            item.write(fileUpload);

                        }
                        catch (Exception ex)
                        {
                            ex.printStackTrace();
                        }
                    }
                }
                String id = (String) params.get("txtID");
                Foods food = rFood.getByID(Integer.parseInt(id));
                if (food != null)
                {
                    food.setImgPath(imgPath);
                    boolean result = rFood.edit(food);
                    if (result)
                    {
                        response.sendRedirect("FoodCO?action=getAll");
                    }
                    else
                    {
                        response.sendRedirect("FoodCO?action=formEditImage");
                    }
                }
            }
        }
        else if (action.equalsIgnoreCase("delete"))
        {
            String id = request.getParameter("id");
            boolean result = rFood.delete(Integer.parseInt(id));
            if (result)
            {
                response.sendRedirect("FoodCO?action=getAll");
            }
            else
            {
                response.sendRedirect("FoodCO?action=getAll");
            }
        }
        else if (action.equalsIgnoreCase("edit"))
        {
            String id = request.getParameter("txtID");
            String category = request.getParameter("cbbFoodType");
            String vegetarian = request.getParameter("ckbVegetarian");
            String price = request.getParameter("txtPrice");
            boolean isVegetarian = false;
            if (vegetarian != null)
            {
                isVegetarian = true;
            }
            Foods food = rFood.getByID(Integer.parseInt(id));
            FoodTypes foodType = rFoodType.getByID(Integer.parseInt(category));
            if (food != null)
            {
                food.setFoodTypes(foodType);
                food.setPrice(Float.parseFloat(price));
                food.setIsVegetarian(isVegetarian);
                boolean result = rFood.edit(food);
                if (result)
                {
                    response.sendRedirect("FoodCO?action=getAll");
                }
                else
                {
                    response.sendRedirect("FoodCO?action=formEditFoodType");
                }
            }
        }
        else if (action.equalsIgnoreCase("viewMenu"))
        {
            List<FoodTypes> types = rFoodType.getAll();
            request.setAttribute("types", types);
            List<Foods> foods = rFood.getAll();
            request.setAttribute("foods", foods);
            RequestDispatcher rd = request.getRequestDispatcher("us_ViewMenu.jsp");
            rd.forward(request, response);
        }
        else if (action.equalsIgnoreCase("getFood"))
        {
            String category = request.getParameter("cbbFoodType");
            if (category.equalsIgnoreCase("viewMenu"))
            {
                response.sendRedirect("FoodCO?action=viewMenu");
            }
            else
            {
                List<Foods> foods = rFood.getFoodByFoodType(category);
                List<FoodTypes> types = rFoodType.getAll();
                request.setAttribute("types", types);
                request.setAttribute("foods", foods);
                request.setAttribute("selectedFoodType", category);
                System.out.println(category);
                RequestDispatcher rd = request.getRequestDispatcher("us_ViewMenu.jsp");
                rd.forward(request, response);
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
        return "Short description";
    }// </editor-fold>
}
